package com.central.apps.handler.cronTask;

import com.central.app.common.quartz.QuartzJob;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
 *
 * @author 李大超
 */
@Component
@Slf4j
@DisallowConcurrentExecution
public class InventoryReorderTask extends QuartzJob {
    @Autowired
    private HandlerService handlerService;

    /**
     * 库存重订购生成采购申请
     *
     * @param context
     * @param jobnum
     * @param jobname
     * @param jobparams
     * @throws JobExecutionException
     */
    @SneakyThrows
    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) throws JobExecutionException {
        // 记录定时任务记录
        handlerService.findBySql("insert into tb_task_log(task_describe) values('匹配今日需要执行采购申请的库存信息，批量生成采购申请')");

        // 查询可重订购、可用余量<安全库存并且未生成采购申请的库存信息
        List<Map<String, Object>> invList = handlerService.findBySql("select * from gq_inventory where isreorder = '1' and avblbalance < reorderminstock and isgeneratepr = '0'");

        if (CollectionUtils.isNotEmpty(invList)) {
            for (Map<String, Object> invMap : invList) {
                generatePR(invMap);
            }
        }
    }

    /**
     * 生成采购申请
     *
     * @param invMap
     */
    private void generatePR(Map<String, Object> invMap) throws Exception {
        String itemnum = MapUtils.getString(invMap,"itemnum");
        String itemdesc = MapUtils.getString(invMap,"itemdesc");
        String storenum = MapUtils.getString(invMap,"storenum");
        String orgcode = MapUtils.getString(invMap,"orgcode");
        String sitecode = MapUtils.getString(invMap,"sitecode");
        String deptcode = MapUtils.getString(invMap,"deptcode");
        int orderqty = MapUtils.getInteger(invMap,"orderqty");
        String orderunit = MapUtils.getString(invMap,"orderunit");
        String model = MapUtils.getString(invMap,"model");

        // 生成采购申请信息
        Map<String, Object> prMap = new HashMap<>(1);

        // 生成采购申请编码
        Map<String, Object> numMap = new HashMap<>();
        handlerService.addBizNum("prApp", "gq_pr", numMap);
        // 查询采购申请编码
        String prnum = (String) numMap.get("prnum");
        prMap.put("prnum", prnum);
        String prDesc = "库存不足定时触发采购申请";
        prMap.put("description", prDesc);

        StringBuilder sb = new StringBuilder();
        sb.append("库房");
        sb.append(storenum);
        sb.append("中");
        sb.append("物料");
        sb.append(itemnum);
        sb.append("库存不足，需要进行采购");
        prMap.put("remarks", sb.toString());

        prMap.put("status", "新建");
        prMap.put("purchasetype", "计划采购");

        // 年、月份
        LocalDate localDate = LocalDate.now();
        prMap.put("year", localDate.getYear());
        prMap.put("month", localDate.getMonthValue());

        // TODO requireddate要求的日期

        // 总公司、分公司、部门编码空值
        prMap.put("orgcode", orgcode);
        prMap.put("sitecode", sitecode);
        prMap.put("deptcode", deptcode);

        handlerService.insert("gq_pr", prMap);

        // 生成采购申请明细信息
        Map<String, Object> prLineMap = new HashMap<>(1);
        prLineMap.put("linetype", "物资");
        prLineMap.put("converttopo", "0");
        prLineMap.put("converttorfq", "0");
        prLineMap.put("prlinenum", "1");
        prLineMap.put("purchasetype", "计划采购");

        prLineMap.put("prnum", prnum);
        prLineMap.put("prdesc", prDesc);
        prLineMap.put("itemnum", itemnum);
        prLineMap.put("itemdesc", itemdesc);
        prLineMap.put("orderqty", orderqty);
        prLineMap.put("orderunit", orderunit);
        prLineMap.put("model", model);

        // 总公司、分公司、部门编码空值
        prLineMap.put("orgcode", orgcode);
        prLineMap.put("sitecode", sitecode);
        prLineMap.put("deptcode", deptcode);

        handlerService.insert("gq_prline", prLineMap);
    }
}
